package com.cn.ant.modules.volunteer.service;

import com.cn.ant.common.persistence.Page;
import com.cn.ant.common.service.BaseService;
import com.cn.ant.common.utils.DateUtils;
import com.cn.ant.common.utils.Identities;
import com.cn.ant.common.utils.StringUtils;
import com.cn.ant.modules.score.entity.SchoolLqRate;
import com.cn.ant.modules.score.service.LqSchoolService;
import com.cn.ant.modules.score.service.SchoolLqRateService;
import com.cn.ant.modules.user.entity.UserMain;
import com.cn.ant.modules.volunteer.dao.VolunteerDao;
import com.cn.ant.modules.volunteer.dao.VolunteerSchoolDao;
import com.cn.ant.modules.volunteer.entity.Volunteer;
import com.cn.ant.modules.volunteer.entity.VolunteerSchool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 志愿组合Service
 * @author 黄根华
 * @version 2015-10-11
 */
@Service
@Transactional(readOnly = true)
public class VolunteerService extends BaseService {

    @Autowired
	private VolunteerDao volunteerDao;
	@Autowired
	private VolunteerSchoolDao volunteerSchoolDao;
	@Autowired
	private SchoolLqRateService schoolLqRateService;
	@Autowired
	private LqSchoolService lqSchoolService;

	public Volunteer get(String id) {
		return volunteerDao.get(id);
	}

	public Volunteer getByCode(String vId){
		return volunteerDao.getByCode(vId);
	}
	
	public List<Volunteer> findList(Volunteer volunteer) {
		return volunteerDao.findList(volunteer);
	}
	
	public Page<Volunteer> findPage(Page<Volunteer> page, Volunteer volunteer) {
	    volunteer.setPage(page);
        page.setList(volunteerDao.findList(volunteer));
        return page;
	}

	public List<Map<String,String>> findVolunteer(String userId) {
		Map<String, String> params = new HashMap<>();
		params.put("userId", userId);
		return volunteerDao.findVolunteer(params);
	}
	
	@Transactional(readOnly = false)
	public void save(Volunteer volunteer) {
	    if (volunteer.getIsNewRecord()) {
            volunteer.preInsert();
            volunteerDao.insert(volunteer);
        } else {
            volunteer.preUpdate();
            volunteerDao.update(volunteer);
        }
	}
	
	@Transactional(readOnly = false)
	public void delete(Volunteer volunteer) {
		volunteerDao.delete(volunteer);
	}

	/**
	 * 删除未收藏的志愿
	 */
	@Transactional(readOnly = false)
	public void deleteUnFavorite() {
		String currDate = DateUtils.formatDate(DateUtils.addMinutes(DateUtils.getCurrDate(), -30),"yyyy-MM-dd HH:mm");
		logger.info("删除的时间点:" + currDate);
		Map<String, String> params = new HashMap<>();
		params.put("createTime", currDate);
		//删除志愿组合
		volunteerDao.deleteUnFavorite(params);
		//删除志愿组合关联的学校
		volunteerSchoolDao.deleteVSchool();
	}

	/**
	 * 根据用户输入的分数产生志愿组合
	 * @param score 分数
	 * @param userMain 考生信息
	 * @param vtype 志愿组合类型
	 *              all:所有组合
	 *				safely:保底型
	 *				steady：稳健型
	 *				danger：冒险性
	 * @param params 志愿组合筛选条件
	 * @return
	 */
	public List<Volunteer> createVolunteer(int score, UserMain userMain,String vtype, Map<String, Object> params) {
		List<Volunteer> volunteerList = new ArrayList<>();
		if (StringUtils.isBlank(vtype)) {
			vtype = "all";
		}
		if (params == null) {
			params = new HashMap<>();
		}
		params.put("kemuType", userMain.getKmType());
		params.put("province", userMain.getAreaCode());
		params.put("batchLevel", userMain.getBatchLevel());
		params.put("score", score);
		params.put("year",lqSchoolService.getCurrYear());
		if (StringUtils.equals(vtype, "all")) {
			//保底型
			params.put("vtype", "safely");
			List<SchoolLqRate> safelyLqRateList = schoolLqRateService.query(params);
			volunteerList.add(generateVolunteer("safely", userMain, score, safelyLqRateList));
			//稳健性
			params.put("vtype", "steady");
			List<SchoolLqRate> steadyLqRateList = schoolLqRateService.query(params);
			volunteerList.add(generateVolunteer("steady", userMain, score, steadyLqRateList));
			//冒险性
			params.put("vtype", "danger");
			List<SchoolLqRate> dangerLqRateList = schoolLqRateService.query(params);
			volunteerList.add(generateVolunteer("danger", userMain, score, dangerLqRateList));
		} else {
			params.put("vtype",vtype);
			List<SchoolLqRate> schoolLqRateList = schoolLqRateService.query(params);
			volunteerList.add(generateVolunteer(vtype, userMain, score, schoolLqRateList));
		}
		return volunteerList;
	}

	private Volunteer generateVolunteer(String vtype,UserMain userMain,int score,List<SchoolLqRate> schoolLqRateList) {
		Volunteer volunteer = new Volunteer();
		volunteer.setVolunteerCode(Identities.generateMainSn());
		String name = StringUtils.equals(vtype, "safely") ? "保底型" : StringUtils.equals(vtype, "steady") ? "稳妥型" : "冒险型";
		volunteer.setName(name + "志愿组合");
		volunteer.setVscore(score);
		volunteer.setVprovince(userMain.getAreaCode());
		volunteer.setVtype(vtype);
		volunteer.setKmType(userMain.getKmType());
		volunteer.setBatchLevel(userMain.getBatchLevel());
		volunteer.setUserId(userMain.getId());
		volunteer.setCreateTime(DateUtils.getCurrDate());
		volunteer.setVolunteerSchoolList(chooseSchool(volunteer, schoolLqRateList, vtype, 5));
		return volunteer;
	}

	/**
	 * 筛选组合中的学校
	 * @param volunteer
	 * @param lqRateList
	 * @param vtype
	 * @param num
	 * @return
	 */
	public List<VolunteerSchool> chooseSchool(Volunteer volunteer, List<SchoolLqRate> lqRateList, String vtype, int num) {
		List<VolunteerSchool> volunteerSchoolList = new ArrayList<VolunteerSchool>();
		if (lqRateList.size() < num) {
			num = lqRateList.size();
		}
		if (num == 0) {
			return volunteerSchoolList;
		}
		int[] idxs = splitSchoolIndex(lqRateList.size(), num);
		for (int i = 0; i < idxs.length; i++) {
			VolunteerSchool volunteerSchool = new VolunteerSchool();
			SchoolLqRate schoolLqRate = lqRateList.get(idxs[i]);
			volunteerSchool.setVId(volunteer.getVolunteerCode());
			volunteerSchool.setSchoolCode(schoolLqRate.getSchoolCode());
			volunteerSchool.setSchoolCodeSn(schoolLqRate.getSchoolCodeSn());
			volunteerSchool.setSchoolName(schoolLqRate.getSchoolName());
			volunteerSchool.setSchoolLevel(i);
			volunteerSchool.setSchoolType("1");;
			volunteerSchool.setLqRate(schoolLqRate.getRate());
			volunteerSchoolList.add(volunteerSchool);
		}
		return volunteerSchoolList;
	}

	/**
	 * 分隔指定的数
	 * @param len : 总长度
	 * @param num : 分隔的份数
	 * @return : 分隔的数组
	 */
	public int[] splitSchoolIndex(int len, int num) {
		int[] indexArr = new int[num];
		int step = len / num;
		if (step == 0) {
			step = 1;
		}
		if (step > 0) {
			for (int i = 0; i < num; i++) {
				int idx = i * step;
				if (idx > len) {
					idx = len;
				}
				indexArr[i] = idx;
			}
		}
		return indexArr;
	}

}